import { reqSaveDir } from '@/api/file'
import { ElMessage } from 'element-plus'
import { openDB } from 'idb'

//定义chatApp子文件夹数组
const subDirectories = ['audio', 'video', 'picture', 'file', 'emoji']

export async function selectAndStoreDirectory(userId: number) {
    if (!(window as any).showDirectoryPicker) {
        return ElMessage.warning('该浏览器不支持读取本地储存，将使用受限功能')
    }

    try {
        //让用户选择一个目录
        const directoryHandle = await (window as any).showDirectoryPicker()

        //创建chatApp目录
        const chatAppDirHandle = await directoryHandle.getDirectoryHandle('chatApp', {
            create: true,
        })

        //在chatApp目录下创建子目录
        for (let i = 0; i < subDirectories.length; i++) {
            await chatAppDirHandle.getDirectoryHandle(subDirectories[i], {
                create: true,
            })
        }

        ElMessage.info('本地储存文件夹创建成功')

        //序列化需要存储的句柄信息
        const directoryInfo = {
            name: directoryHandle.name,
            kind: directoryHandle.kind,
        }

        //将目录信息存储到后端数据库
        const data = {
            userId: userId,
            directoryInfo: directoryInfo, //仅存储元数据
        }
        await reqSaveDir(data)
        //存储目录句柄到IndexedDB
        await saveDirectoryHandleToIndexedDB(directoryHandle)
    } catch (error) {
        console.error('无法访问文件系统:', error)
    }
}

//将目录句柄存储到IndexedDB
async function saveDirectoryHandleToIndexedDB(handle: FileSystemDirectoryHandle) {
    const db = await openDB('directoryDB', 2, {
        upgrade(db) {
            //确保'directories'对象存储已经被创建
            if (!db.objectStoreNames.contains('directories')) {
                db.createObjectStore('directories')
            }
        },
    })
    await db.put('directories', handle, 'chatAppDirectory')
}

//从IndexedDB读取目录句柄
export async function getDirectoryHandleFromIndexedDB(): Promise<FileSystemDirectoryHandle | null> {
    const db = await openDB('directoryDB', 2, {
        upgrade(db) {
            //确保对象仓库已经存在
            if (!db.objectStoreNames.contains('directories')) {
                db.createObjectStore('directories')
            }
        },
    })
    const handle = await db.get('directories', 'chatAppDirectory')
    return handle || null
}

//检查chatApp及其子目录是否存在IndexedDB中
export async function checkDirectories(userId: number) {
    try {
        //获取存储的目录句柄
        const directoryHandle = await getDirectoryHandleFromIndexedDB()

        if (!directoryHandle) {
            //如果没有存储的句柄，用户需要选择目录
            ElMessage.info('未找到存储文件的目录句柄，请选择目录')
            await selectAndStoreDirectory(userId)
            return
        } else {
            ElMessage.info('已恢复对目录的访问')
        }
    } catch (error) {
        //如果出现错误，可以重新创建
        await selectAndStoreDirectory(userId)
    }
}
